package avicit.bdp.dgs.qa.service;

import avicit.bdp.approval.api.impl.QualityApprovalApi;
import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.dto.approval.ApprovalDTO;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.common.utils.VersionUtil;
import avicit.bdp.core.constant.Constants;
import avicit.bdp.core.enums.DataStateEnum;
import avicit.bdp.dgs.qa.dao.RuleTemplateDAO;
import avicit.bdp.dgs.qa.dto.*;
import avicit.bdp.dgs.qa.utils.enums.*;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.properties.PlatformConstant;
import avicit.platform6.core.rest.msg.QueryRespBean;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * @金航数码科技有限责任公司
 * @作者：developer
 * @邮箱：developer@avic-digital.com
 * @创建时间： 2023-03-15
 * @类说明：RuleTemplateService
 * @修改记录：
 * @注意事项：
 * @主要功能：规则模板Service
 */
@Service
public class RuleTemplateService extends BaseService<RuleTemplateDAO, RuleTemplateDTO> {
    private static final Logger logger = LoggerFactory.getLogger(RuleTemplateService.class);

    private static final String RULE_TMPL_TYPE = "ruleTemplateType";

    public static final String IOTDB = "iotdb";

    @Autowired
    private RuleTemplateHistoryService historyService;

    @Autowired
    private ConvertColumnClient convertColumnClient;

    @Autowired
    private QualityApprovalApi approvalRpc;

    @Autowired
    private RuleTemplateArguementService arguementService;

    @Autowired
    private QaDataSourceService qaDataSourceService;

    /**
     * 新增规则模板
     *
     * @param ruleTemplateDTO
     * @return
     */
    @Transactional
    public Boolean addRuleTemplate(RuleTemplateDTO ruleTemplateDTO) {
        // step1:合法性检查
        checkAddValid(ruleTemplateDTO);

        // step2:持久化到DB
        save2DB(ruleTemplateDTO);

        return true;
    }

    /**
     * 删除/批量删除规则模板，多个id使用英文逗号隔开
     *
     * @param id
     * @return
     */
    @Transactional
    public Integer deleteRuleTemplate(String id) {
        if (StringUtils.isBlank(id)) {
            return 0;
        }

        for (String ruleTemplateId : Arrays.asList(id.trim().split(Constants.COMMA))) {
            // 如果有模板引用，不能删除
            Page<TemplateRelationDTO> ruleDTOS = this.mapper.queryRuleTmplRel(ruleTemplateId);
            if (CollectionUtils.isNotEmpty(ruleDTOS)) {
                throw new BusinessException("质量任务正在引用规则模板，不能删除.");
            }

            this.mapper.deleteRuleTmplByCond(Arrays.asList(ruleTemplateId));

            // 删除模板参数
            this.arguementService.deleteArguementByCond(id);
        }

        String logTitle = "删除规则模板：【" + id + "】";
        BdpLogUtil.log("规则模板模块", logTitle, PlatformConstant.OpType.delete);

        return 0;
    }

    /**
     * 修改规则模板
     *
     * @param ruleTemplateDTO
     * @return
     */
    @Transactional
    public Boolean updateRuleTemplate(RuleTemplateDTO ruleTemplateDTO) {
        // step1:合法性检查
        checkUpdateValid(ruleTemplateDTO);

        // step2:持久化到DB
        update2DB(ruleTemplateDTO);

        return true;
    }

    /**
     * 根据主键ID查询规则模板详情
     *
     * @param id
     * @return
     */
    @Transactional
    public RuleTemplateDTO getRuleTemplateDetail(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }

        RuleTemplateDTO dto = this.mapper.getRuleTmplDetail(id);
        if (dto == null) {
            return null;
        }

        // 转换
        valueConvert(Arrays.asList(dto));
        BdpLogUtil.log4Query(dto);
        return dto;
    }

    /**
     * 分页查询规则模板
     *
     * @param measureType
     * @param templateType
     * @param ruleType
     * @param ruleDimension
     * @param keyWords
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Transactional
    public QueryRespBean<RuleTemplateDTO> queryRuleTemplate(Integer measureType, Integer templateType, Integer ruleType,
                                                            Integer ruleDimension, String keyWords, Integer pageNo, Integer pageSize) {
        QueryRespBean<RuleTemplateDTO> queryRespBean = new QueryRespBean<>();

        // step1：分页查询数据权限列表
        List<String> wordSecretList = ThreadContextHelper.getWordSecretList();
        com.github.pagehelper.PageHelper.startPage(pageNo, pageSize);
        Page<RuleTemplateDTO> queryRet = this.mapper.queryRuleTmplByCond(measureType, templateType, ruleType, ruleDimension, keyWords, wordSecretList);
        queryRespBean.setResult(queryRet);

        // step2；转换
        valueConvert(queryRet.getResult());
        BdpLogUtil.log4Query(queryRespBean);
        return queryRespBean;
    }

    /**
     * 判读模板名称是否重复
     * 注意：
     * 1、同一分类层架下，模板名字不能重复
     *
     * @param id
     * @param measureType
     * @param name
     * @return true:重复；false :不重复
     */
    @Transactional
    public Boolean isSameName(String id, Integer measureType, String name) {
        long count = this.mapper.selectNameCount(id, name, measureType);
        if (count > 0) {
            return true;
        }

        return false;
    }

    /**
     * 获取规则模板版本
     *
     * @param id
     * @return
     */
    @Transactional
    public String getVersion(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }

        RuleTemplateDTO dto = this.selectByPrimaryKey(id);
        if (dto == null) {
            logger.error("根据ID未找到模板，id=" + id + "，更新失败");
            return null;
        }

        String maxVersion = this.historyService.getMaxVersion(id);
        if (StringUtils.isEmpty(maxVersion)) {
            return Constants.VERSION_PREFIX + VersionUtil.generateVersion2Default();
        }

        String[] strs = maxVersion.trim().split(Constants.VERSION_PREFIX);
        if (strs.length != 2) {
            logger.warn("当前最大版本号为：" + maxVersion + ",templateId:" + id);
            return Constants.VERSION_PREFIX + VersionUtil.generateVersion2Default();
        }

        return Constants.VERSION_PREFIX + VersionUtil.generateVersion2Next(strs[1]);
    }

    /**
     * 发布新版本
     *
     * @param id
     * @param version
     * @return
     */
    @Transactional
    public Boolean publishRuleTemplate(String id, String version) {
        if (StringUtils.isBlank(id)) {
            throw new BusinessException("模板ID为空，发布失败.");
        }
        if (StringUtils.isBlank(version)) {
            throw new BusinessException("模板版本为空，发布失败.");
        }

        // 更新模板
        RuleTemplateDTO dto = this.selectByPrimaryKey(id);
        if (dto == null) {
            throw new BusinessException("根据ID未找到模板，id=" + id + "，更新失败");
        }
        dto.setState(DataStateEnum.UNDER_APPROVAL.getCode());//审批中
        update2DB(dto);

        // 向审批中心发送发布请求
        dto.setTemplateVersion(version);
        return relase2ApprovalCenter(dto);
    }


    /**
     * 版本下线
     *
     * @param id
     * @return
     */
    @Transactional
    public Boolean offline(String id) {
        if (StringUtils.isBlank(id)) {
            throw new BusinessException("模板历史版本ID为空，下线失败.");
        }

        RuleTemplateHistoryDTO historyDTO = this.historyService.selectByPrimaryKey(id);
        if (historyDTO == null) {
            throw new BusinessException("根据ID未找到历史版本，id=" + id + "，更新失败");
        }

        historyDTO.setState(DataStateEnum.DEPRECATED.getCode());// 已废止
        this.historyService.updateByPrimaryKeySelective(historyDTO);

        return true;
    }

    /**
     * /**
     * 删除/批量删除模板历史版本，多个id使用英文逗号隔开
     *
     * @param id
     * @return
     */
    @Transactional
    public Integer deleteRuleTemplateHistory(String id) {
        if (StringUtils.isBlank(id)) {
            return 0;
        }

        String logTitle = "删除规则模板：【" + id + "】";
        BdpLogUtil.log("规则模板模块", logTitle, PlatformConstant.OpType.delete);
        return this.historyService.deleteRuleTmplHistoryByCond(Arrays.asList(id.trim().split(Constants.COMMA)));
    }

    /**
     * 获取历史版本
     *
     * @param id
     * @return
     */
    @Transactional
    public List<RuleTemplateHistoryDTO> getHistory(String id) {
        if (StringUtils.isBlank(id)) {
            throw new BusinessException("模板ID为空，获取历史版本失败.");
        }

        return this.historyService.getRuleTmplHistoryList(id);
    }

    /**
     * 根据主键ID查询规则模板详情
     *
     * @param id
     * @return
     */
    @Transactional
    public RuleTemplateHistoryDTO getRuleTmplHistoryDetail(String id) {
        return this.historyService.getRuleTmplHistoryDetail(id);
    }

    /**
     * 版本对比
     *
     * @param ruleTemplateId1
     * @param ruleTemplateId2
     * @return
     */
    @Transactional
    public List<RuleTemplateHistoryDTO> compareRuleTemplate(String ruleTemplateId1, String ruleTemplateId2) {
        List<RuleTemplateHistoryDTO> historyList = Lists.newArrayList();

        RuleTemplateHistoryDTO historyDTO1 = this.historyService.getRuleTmplHistoryDetail(ruleTemplateId1);
        if (historyDTO1 != null) {
            historyList.add(historyDTO1);
        }

        RuleTemplateHistoryDTO historyDTO2 = this.historyService.getRuleTmplHistoryDetail(ruleTemplateId2);
        if (historyDTO2 != null) {
            historyList.add(historyDTO2);
        }

        return historyList;
    }

    /**
     * 导入规则模板
     *
     * @param measureType 校验类型
     * @param override    true：覆盖；false：不覆盖
     * @param file
     * @return
     */
    @Transactional
    public Boolean importRuleTemplate(Integer measureType, Boolean override, MultipartFile file) {
        throw new BusinessException("模板导入功能暂不支持，敬请期待。");
    }

    /**
     * 导出规则模板
     *
     * @param fileName
     * @param id
     * @param response
     */
    @Transactional
    public void exportRuleTemplate(String fileName, String id, HttpServletResponse response) {
        throw new BusinessException("模板导出功能暂不支持，敬请期待。");
    }

    /**
     * 获取规则模板分类树
     * 注意：
     * 版本1：依据“规则类型-规则维度-模板类型-模板”分类
     * 版本2：依据“规则类型-模板”两级分类体系，modified by wm，2023-06-15 14:29
     * 版本3：依据“规则类型-模板”两级分类体系，针对Iotdb数据源特殊处理，仅返回适用的模板列表
     *
     * @param measureType
     * @param templateType
     * @param jobId
     * @return
     */
    @Transactional
    public List<RuleTemplateDTO> getTemplateTree(Integer measureType, Integer templateType, String jobId) {
        List<RuleTemplateDTO> tree = new ArrayList<>();

        // 获取所有模板
        List<RuleTemplateDTO> dtoList = this.selectListAll();
        if (CollectionUtils.isEmpty(dtoList)) {
            return tree;
        }
        // 根据模板类型过滤
        if (templateType != null) {
            dtoList = dtoList.stream().filter(item -> item.getTemplateType() == templateType).collect(Collectors.toList());
        }
        // 根据校验类型过滤
        if (measureType != null) {
            dtoList = dtoList.stream().filter(item -> item.getMeasureType() == measureType).collect(Collectors.toList());
        }
        // 根据数据源类型过滤
        /**
         * 修改说明：iotdb校验任务，仅返回iotdb模板，其他不做限制
         * 修改人：wm
         * 修改时间：2023-11-13 16:32
         */
        if (TemplateType.BUILT_IN.getCode() == templateType) {
            String dbType = this.qaDataSourceService.getDbTypeByJobId(jobId);
            if (StringUtils.isNotEmpty(dbType) && dbType.toLowerCase().equals(IOTDB)) {
                dtoList = dtoList.stream().filter(item -> item.getName().toLowerCase().contains(IOTDB)).collect(Collectors.toList());
            } else {
                dtoList = dtoList.stream().filter(item -> !(item.getName().toLowerCase().contains(IOTDB))).collect(Collectors.toList());
            }
        }

        String dbType = this.qaDataSourceService.getDbTypeByJobId(jobId);
        if (TemplateType.BUILT_IN.getCode() == templateType
                && StringUtils.isNotEmpty(dbType)
                && dbType.toLowerCase().equals(IOTDB)) {
            dtoList = dtoList.stream().filter(item -> item.getName().toLowerCase().contains(IOTDB)).collect(Collectors.toList());
        }

        // 树结构初始化
        for (RuleType ruleType : RuleType.values()) {
            RuleTemplateDTO ruleTypeNode = new RuleTemplateDTO();
            ruleTypeNode.setName(ruleType.getDesc());
            ruleTypeNode.setLeaf(0);// 0:非叶子节点；1:叶子节点
            ruleTypeNode.setRuleType(ruleType.getCode());
            ruleTypeNode.setChildren(new ArrayList<>());

            tree.add(ruleTypeNode);
        }

        // 规则模板节点初始化(仅获取“已发布“状态下的模板)
        // 规则模板取消版本管理，不再依据状态过滤，modifed by wm，2023-06-26 14:08
        for (RuleTemplateDTO ruleTypeNode : tree) {
            for (RuleTemplateDTO dto : dtoList) {
                if (dto.getRuleType() == ruleTypeNode.getRuleType()) {
                    dto.setLeaf(1);
                    ruleTypeNode.getChildren().add(dto);
                }
            }
        }

        return tree;
    }

    /**
     * 查询规则模板数量
     *
     * @return
     */
    @Transactional
    public Long countRuleTemplate(String startTime, String endTime, List<String> wordSecretList) {
        return this.mapper.countTemplate(startTime, endTime, wordSecretList);
    }

    /**
     * 查询规则模板参数
     *
     * @param templateId 规则模板ID
     * @return
     */
    @Transactional
    public List<RuleTemplateArguementDTO> getRuleArguementList(String templateId) {
        if (StringUtils.isEmpty(templateId)) {
            return new ArrayList<>();
        }

        RuleTemplateDTO ruleTemplate = this.selectByPrimaryKey(templateId);
        if (ruleTemplate == null) {
            logger.error("未找到规则模板，查询模板参数失败，id={}", templateId);
            return new ArrayList<>();
        }

        List<RuleTemplateArguementDTO> argumentList = this.arguementService.getArgumentListByTemplateId(templateId);
        if (CollectionUtils.isEmpty(argumentList)) {
            return new ArrayList<>();
        }

        // 设置参数类型名称
        for (RuleTemplateArguementDTO arg : argumentList) {
            if (arg.getType() != null) {
                arg.setTypeName(ArgumentType.getDescByCode(arg.getType()));
            }
            if (arg.getDefaultValue() != null) {
                arg.setDefaultValueList(JSONObject.parseObject(arg.getDefaultValue(), List.class));
            }
        }

        return argumentList;
    }

    /**
     * 正则表达式合法性校验
     *
     * @param regexp 正则表达式
     * @param value  待校验值
     * @return
     */
    public boolean checkRegexpValid(String regexp, String value) {
        if (StringUtils.isEmpty(regexp)) {
            return true;
        }

        Pattern pattern = Pattern.compile(regexp);
        Matcher matcher = pattern.matcher(value);

        return matcher.find();
    }

    /**
     * 接收审批中心通知
     *
     * @param approvalList
     * @return
     */
    public boolean receiveMsgFromApprovalCenter(List<ApprovalDTO> approvalList) {
        if (CollectionUtils.isEmpty(approvalList)) {
            return true;
        }

        logger.warn("接收审批结果:\n" + JSONObject.toJSONString(approvalList));

        for (ApprovalDTO approval : approvalList) {
            if (approval == null) {
                continue;
            }
            if (StringUtils.isAnyEmpty(approval.getBusinessId(), approval.getBusinessVersion())) {
                continue;
            }
            if (approval.getApprovalResultType() == null) {
                continue;
            }

            RuleTemplateDTO ruleTemplate = this.mapper.selectByPrimaryKey(approval.getBusinessId());
            if (ruleTemplate == null) {
                continue;
            }
            if (approval.getApprovalResultType().equals(0)) {// 审批通过，设置为“已发布”状态
                ruleTemplate.setState(DataStateEnum.PUBLISHED.getCode());
            } else if (approval.getApprovalResultType().equals(1)) {// 审批不通过通过，设置为“已驳回”状态
                ruleTemplate.setState(DataStateEnum.REJECTED.getCode());
            } else {
                continue;
            }
            ruleTemplate.setTemplateVersion(approval.getBusinessVersion());

            this.updateByPrimaryKeySelective(ruleTemplate);
            saveHistory2DB(ruleTemplate);
        }

        return true;
    }

    /**
     * 查询指定规则模板的引用关系
     *
     * @param id
     * @param pageNo
     * @param pageSize
     * @return
     */
    public QueryRespBean<TemplateRelationDTO> queryRuleTemplateRelationShip(String id, Integer pageNo, Integer pageSize) {
        QueryRespBean<TemplateRelationDTO> queryRespBean = new QueryRespBean<>();

        com.github.pagehelper.PageHelper.startPage(pageNo, pageSize);
        Page<TemplateRelationDTO> queryRet = this.mapper.queryRuleTmplRel(id);
        queryRespBean.setResult(queryRet);

        // step3；转换
        templateRelationConvert(queryRet.getResult());

        return queryRespBean;
    }

    /**
     * 获取文件校验内置模板
     *
     * @return
     */
    public List<RuleTemplateDTO> getFileTemplateList() {
        return this.mapper.getFileTemplateList();
    }

    /**
     * 新增规则模板合法性检查
     *
     * @param ruleTemplateDTO
     */
    private void checkAddValid(RuleTemplateDTO ruleTemplateDTO) {
        if (ruleTemplateDTO == null) {
            throw new BusinessException("入参为空.");
        }
        if (StringUtils.isBlank(ruleTemplateDTO.getName())) {
            throw new BusinessException("规则模板名字为空.");
        }
        if (ruleTemplateDTO.getRuleType() == null) {
            throw new BusinessException("模板类型为空.");
        }
        if (ruleTemplateDTO.getRuleType() == null) {
            throw new BusinessException("规则类型为空.");
        }
        if (ruleTemplateDTO.getRuleDimension() == null) {
            throw new BusinessException("维度为空.");
        }
        if (ruleTemplateDTO.getMeasureType() == null) {
            throw new BusinessException("校验类型为空.");
        }
        if (ruleTemplateDTO.getStatDataType() == null) {
            throw new BusinessException("统计数值类型为空.");
        }
        if (StringUtils.isBlank(ruleTemplateDTO.getOutputName())) {
            throw new BusinessException("模板输出名称为空.");
        }
        if (StringUtils.isBlank(ruleTemplateDTO.getCustomSQL())) {
            throw new BusinessException("自定义SQL为空.");
        }
    }

    /**
     * 修改规则模板合法性检查
     *
     * @param ruleTemplateDTO
     */
    private void checkUpdateValid(RuleTemplateDTO ruleTemplateDTO) {
        if (ruleTemplateDTO == null) {
            throw new BusinessException("入参为空.");
        }
        if (StringUtils.isBlank(ruleTemplateDTO.getId())) {
            throw new BusinessException("规则模板Id为空.");
        }
    }

    /**
     * 持久化到DB
     *
     * @param ruleTemplateDTO
     */
    private void save2DB(RuleTemplateDTO ruleTemplateDTO) {
        if (ruleTemplateDTO != null) {
            ruleTemplateDTO.setId(ComUtil.getId());
            //状态,0:编辑中、1:审批中、2:已驳回、3：已发布、9：已废止
            ruleTemplateDTO.setState(DataStateEnum.PUBLISHED.getCode());
            ruleTemplateDTO.setVersion(0L);

            // 持久化
            this.insert(ruleTemplateDTO);

            // 审计日志
            BdpLogUtil.log4Insert(ruleTemplateDTO);
        }
    }

    /**
     * 历史版本持久化到DB
     *
     * @param dto
     */
    private void saveHistory2DB(RuleTemplateDTO dto) {

        RuleTemplateHistoryDTO historyDTO = new RuleTemplateHistoryDTO();
        BeanUtils.copyProperties(dto, historyDTO);
        historyDTO.setId(ComUtil.getId());
        historyDTO.setTemplateId(dto.getId());
        historyDTO.setTemplateVersion(dto.getTemplateVersion());
        historyDTO.setState(dto.getState());

        // 持久化
        this.historyService.insert(historyDTO);

        // 审计日志
        BdpLogUtil.log4Insert(historyDTO);
    }

    /**
     * 更新DB
     *
     * @param newDto
     */
    private void update2DB(RuleTemplateDTO newDto) {
        if (newDto == null) {
            return;
        }

        RuleTemplateDTO oldDto = this.selectByPrimaryKey(newDto.getId());
        if (oldDto == null) {
            throw new BusinessException("根据ID未找到模板，id=" + newDto.getId() + "，更新失败");
        }

        // 持久化
        newDto.setCreatedBy(oldDto.getCreatedBy());
        this.updateByPrimaryKeySelective(newDto);

        // 审计日志
        BdpLogUtil.log4Update(newDto, oldDto);
    }

    /**
     * 通过平台API将字段值转换为名称，包括通用选择组件、通用代码
     *
     * @param dtoList
     */
    private void valueConvert(List<RuleTemplateDTO> dtoList) {
        if (CollectionUtils.isEmpty(dtoList)) {
            return;
        }

        // 设置创建者名称
        Map<String, Set<String>> convertFormData = new HashMap<>();
        for (RuleTemplateDTO dto : dtoList) {
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, dto.getCreatedBy());
            BusinessUtil.createConvertSet(convertFormData, Constants.BDP_DATA_SECRET_LEVEL_KEY, dto.getSecretLevel());
        }
        if (convertFormData.size() > 0) {
            //获取请求结果
            Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
            //循环设置Alias或Name的值
            for (RuleTemplateDTO dto : dtoList) {
                dto.setCreatedBy(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER, dto.getCreatedBy()));
                dto.setSecretLevelName(BusinessUtil.convertFormat(
                        convertResultData, Constants.BDP_DATA_SECRET_LEVEL_KEY, dto.getSecretLevel()));
            }
        }

        // 设置枚举类型
        for (RuleTemplateDTO dto : dtoList) {
            dto.setStateName(DataStateEnum.getDescByCode(dto.getState()));
            dto.setTemplateTypeName(TemplateType.getDescByCode(dto.getTemplateType()));
            dto.setRuleTypeName(RuleType.getDescByCode(dto.getRuleType()));
            dto.setRuleDimensionName(RuleDimension.getDescByCode(dto.getRuleDimension()));
            dto.setMeasureTypeName(MeasureType.getDescByCode(dto.getMeasureType()));
            dto.setStatDataTypeName(StatDataType.getDescByCode(dto.getStatDataType()));
        }
    }

    /**
     * 通过平台API将字段值转换为名称，包括通用选择组件、通用代码
     *
     * @param dtoList
     */
    private void templateRelationConvert(List<TemplateRelationDTO> dtoList) {
        if (CollectionUtils.isEmpty(dtoList)) {
            return;
        }

        // 设置创建者名称
        Map<String, Set<String>> convertFormData = new HashMap<>();
        for (TemplateRelationDTO dto : dtoList) {
            if (StringUtils.isNotEmpty(dto.getCreatedBy())) {
                BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, dto.getCreatedBy());
            }
        }
        if (convertFormData.size() > 0) {
            //获取请求结果
            Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
            //循环设置Alias或Name的值
            for (TemplateRelationDTO dto : dtoList) {
                if (StringUtils.isNotEmpty(dto.getCreatedBy())) {
                    dto.setCreatedBy(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER, dto.getCreatedBy()));
                }
            }
        }

        // 设置枚举类型
        for (TemplateRelationDTO dto : dtoList) {
            dto.setMeasureTypeName(MeasureType.getDescByCode(dto.getMeasureType()));
        }
    }

    /**
     * 向审批中心发送发布请求
     *
     * @param ruleTemplate
     * @return
     */
    private boolean relase2ApprovalCenter(RuleTemplateDTO ruleTemplate) {
        if (StringUtils.isAnyEmpty(ruleTemplate.getId(), ruleTemplate.getName(), ruleTemplate.getTemplateVersion())) {
            throw new BusinessException(String.format("发布版本失败，模板ID：%s，模板名称：%s，模板版本：%s，有空值.",
                    ruleTemplate.getId(), ruleTemplate.getName(), ruleTemplate.getTemplateVersion()));
        }

        ApprovalDTO approvalDTO = new ApprovalDTO();
        approvalDTO.setBusinessId(ruleTemplate.getId());
        approvalDTO.setBusinessName(ruleTemplate.getName());
        approvalDTO.setBusinessVersion(ruleTemplate.getTemplateVersion());

        return this.approvalRpc.release(Arrays.asList(approvalDTO));
    }
}
